package com.gsp.gspframework.util;

import org.apache.commons.lang3.StringUtils;

public final class CastUtil {

    /**
     * 转换为String
     */
    public static String castString(Object o) {
        return castString(o, "");
    }

    /**
     * 转换为String
     */
    public static String castString(Object o, String defaultValue) {
        return o != null ? String.valueOf(o) : defaultValue;
    }

    /**
     * 转换为Double
     */
    public static double castDouble(Object o) {
        return castDouble(o, 0.0);
    }

    /**
     * 转换为Double
     */
    public static double castDouble(Object o, double defaultValue) {
        double doubleValue = defaultValue;
        if (o != null) {
            String stringValue = castString(o);
            if (StringUtils.isNotEmpty(stringValue)) {
                try {
                    doubleValue = Double.parseDouble(stringValue);
                } catch (NumberFormatException e) {
                    doubleValue = defaultValue;
                }
            }
        }
        return doubleValue;
    }

    /**
     * 转换为Long
     */
    public static long castLong(Object o) {
        return castLong(o, 0L);
    }

    /**
     * 转换为Long
     */
    public static long castLong(Object o, long defaultValue) {
        long longValue = defaultValue;
        if (o != null) {
            String stringValue = castString(o);
            if (StringUtils.isNotEmpty(stringValue)) {
                try {
                    longValue = Long.parseLong(stringValue);
                } catch (NumberFormatException e) {
                    longValue = defaultValue;
                }
            }
        }
        return longValue;
    }

    /**
     * 转换为Int
     */
    public static int castInt(Object o) {
        return castInt(o, 0);
    }

    /**
     * 转换为Int
     */
    public static int castInt(Object o, int defaultValue) {
        int intValue = defaultValue;
        if (o != null) {
            String stringValue = castString(o);
            if (StringUtils.isNotEmpty(stringValue)) {
                try {
                    intValue = Integer.parseInt(stringValue);
                } catch (NumberFormatException e) {
                    intValue = defaultValue;
                }
            }
        }
        return intValue;
    }

    /**
     * 转换为Boolean
     */
    public static boolean castBoolean(Object o) {
        return castBoolean(o, false);
    }

    /**
     * 转换为Boolean
     */
    public static boolean castBoolean(Object o, boolean defaultValue) {
        boolean booleanValue = defaultValue;
        if (o != null) {
            String stringValue = castString(o);
            booleanValue = Boolean.parseBoolean(stringValue);
        }
        return booleanValue;
    }
}
